<template>
  <el-form ref="form" :rules="loginRules" :model="form">
    <el-col :span="24">
      <el-form-item prop="mobile">
        <el-input
          v-model="form.mobile"
          placeholder="请输入手机号"
          type="number"
          @wheel.native.prevent="stopScrollFun($event)"
          oninput="if(value.length > 11) value=value.slice(0, 11)"
          @keydown.native="
            (e) =>
              ((e.ctrlKey || e.metaKey) &&
                ['c', 'v', 'a', 'x'].includes(e.key.toLowerCase())) ||
              /[0-9]/.test(e.key) ||
              [
                'Backspace',
                'Tab',
                'ArrowLeft',
                'ArrowRight',
                'Enter',
                'Delete',
              ].includes(e.key) ||
              e.preventDefault()
          "
        ></el-input>
      </el-form-item>
    </el-col>
    <el-col :span="24">
      <el-form-item prop="password">
        <el-input
          v-model="form.password"
          placeholder="请输入密码"
          @keyup.enter.native="handleSubmit"
          class="passwordInput"
          ref="passwordInput"
          :maxlength="20"
          @input="handleInput"
          :type="inputType"
        >
          <template #append>
            <div @click="togglePassword" class="password-toggle">
              <img
                :src="passwordShow ? eyeOpenImg : eyeCloseImg"
                alt="切换密码显示"
                class="password-toggle-img"
              />
            </div>
          </template>
        </el-input>
      </el-form-item>
    </el-col>
    <el-col :span="15">
      <el-form-item prop="code">
        <el-input
          v-model.trim="form.code"
          placeholder="请输入图形码"
          @keyup.enter.native="handleSubmit"
          :maxlength="6"
        />
      </el-form-item>
    </el-col>
    <el-col :span="9">
      <div class="code">
        <img :src="imgPicture" alt="" @click="getPicture" />
      </div>
    </el-col>
    <el-col :span="24">
      <el-form-item>
        <div class="bottombuttons">
          <el-button type="primary" @click="handleSubmit" :loading="loading">
            登录
          </el-button>
          <div class="changeFormButtons">
            <p @click="changeForm('register')" class="changeForm">注册账号</p>
            <p @click="changeForm('forget')" class="changeForm">忘记密码</p>
          </div>
        </div>
      </el-form-item>
    </el-col>
  </el-form>
</template>

<script>
import { validChinesePhoneNumber } from "@/utils/validate";
import { captchaInit } from "@/api/user";
import { burryPointForLogin } from "@/api/data";
import axios from "axios";
import qs from "qs";
export default {
  name: "loginForm",
  data() {
    const validateChinesePhoneNumber = (rule, value, callback) => {
      if (!validChinesePhoneNumber(value)) {
        callback(new Error("请输入正确的手机号码"));
      }
      callback();
    };
    return {
      eyeOpenImg: "//img3.job1001.com/data_center/images/eyeOpen.png",
      eyeCloseImg: "//img3.job1001.com/data_center/images/eyeClose.png",
      codeInfoText: "发送验证码",
      disabledCatpchaFlash: false,
      captchaId: "",
      imgPicture: "",
      form: {
        mobile: "",
        password: "",
        code: "",
      },
      loginRules: {
        mobile: [
          {
            required: true,
            trigger: "blur",
            validator: validateChinesePhoneNumber,
          },
        ],
        password: [{ required: true, trigger: "blur", message: "请输入密码" }],
      },
      loading: false,
      passwordShow: false,
    };
  },
  computed: {
    inputType() {
      return this.passwordShow ? "text" : "password"; // 使用计算属性来动态返回类型
    },
  },
  created() {
    document.title = "登录";
    this.initCaptcha();
  },
  methods: {
    reqReportLoginAction() {
      const params = {
        rightId: "-2",
        cardType: localStorage.getItem("cardType"),
        description: "使用了职业大全",
        patform: 2,
        personId: "-1",
      };
      burryPointForLogin(params)
        .then((res) => {
          if (res.code == 200) {
          }
        })
        .catch((e) => {
          console.log(e);
        });
    },
    togglePassword() {
      this.passwordShow = !this.passwordShow;
      // 切换输入框类型
      this.$refs.passwordInput.type = this.passwordShow ? "text" : "password";
    },
    handleInput(value) {
      // 正则表达式：只允许英文字母、数字和特殊字符
      const validChars = value.replace(/[^a-zA-Z0-9._~!@#$^&*()\-+=]/g, "");

      // 将过滤后的内容更新到 password 中
      this.form.password = validChars;
    },
    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          //通过验证
          this.loading = true;
          const params = {
            grant_type: "password",
            mobile: this.form.mobile,
            username: this.form.mobile,
            password: this.form.password,
            accountType: "appClientZt",
            client_id: "jGKuZdBW7pAsKBNw",
            client_secret: "5e03b32605fe4d50b2d5b4e8145655dc",
            code: this.form.code,
            captchaId: this.captchaId,
          };

          axios
            .post(
              process.env.VUE_APP_BACK_API + "api-auth/oauth/token",
              qs.stringify(params),
              {
                headers: {
                  "Content-Type": "application/x-www-form-urlencoded",
                },
              }
            )
            .then((res) => {
              if (res.data.code == 200) {
                // 登录成功处理
                this.$message.success("登录成功！");
                // 存储手机号码
                localStorage.setItem("mobile", this.form.mobile);
                // 注意两层data
                localStorage.setItem(
                  "token",
                  res.data.data.tokenHead + "" + res.data.data.token
                );
                localStorage.removeItem("userInfo");
                localStorage.setItem("roleType", 10);
                localStorage.setItem("origin", 'loginPage');
                const query = { ...this.$route.query, origin: "loginPage" } || {};
                this.reqReportLoginAction();
                this.$bus.$emit("generalReportAction", {
                  etId: 40013,
                  personId: "-1",
                  cardType: localStorage.getItem("cardType"),
                  jumpSource: 60,
                  sourceType: 60,
                });
                setTimeout(() => {
                  console.log("query", query);
                  this.$router.push({ name: "position", query });
                }, 300);
              } else {
                this.$message.error(res.data.status_desc || "请重试！");
                this.getPicture();
              }
            })
            .catch((e) => {
              this.$message.error(e.response?.data?.status_desc || "请重试！");

              this.getPicture();
              console.log(e);
            })
            .finally(() => {
              this.loading = false;
            });
        } else {
          //console.log("error submit");

          return false;
        }
      });
    },
    changeForm(type) {
      this.$store.dispatch("user/setFormType", type);
    },
    //初始化并获取验证码
    async initCaptcha() {
      const res = await captchaInit();
      if (res.code == 200) {
        this.captchaId = res.data;
        this.imgPicture =
          process.env.VUE_APP_BACK_API +
          "api-auth/common/captcha/draw/" +
          res.data;
      } else {
        this.$message({
          type: "error",
          message: res.status_desc,
        });
      }
    },
    getPicture() {
      //500毫秒内最多获取一次；
      if (this.disabledCatpchaFlash) return;
      this.initCaptcha();
      this.disabledCatpchaFlash = true;
      setTimeout(() => {
        this.disabledCatpchaFlash = false;
      }, 1000);
    },
    stopScrollFun(evt) {
      evt = evt || window.event;
      if (evt.preventDefault) {
        // Firefox
        evt.preventDefault();
        evt.stopPropagation();
      } else {
        // IE
        evt.cancelBubble = true;
        evt.returnValue = false;
      }
      return false;
    },
  },
};
</script>

<style lang="scss">
// 写在这里才生效？？？
/* 去掉 Chrome 浏览器的数字输入框箭头 */
input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

/* 去掉 Firefox 浏览器的数字输入框箭头 */
input[type="number"] {
  -moz-appearance: textfield;
}
</style>

<style lang="scss" scoped>
.passwordInput {
  ::v-deep .el-input__inner {
    border-right: 0;
    border-radius: 3px 0px 0px 3px;
  }
  ::v-deep .el-input-group__append {
    border-radius: 2px;
    background: #f4f6fa;
    border: 1px solid #e3e8ef;
    border-left: 0;
    padding: 0;
    width: 42px;
  }
  ::v-deep .el-input-group__append,
  .el-input-group__prepend {
    padding: 0;
  }
  .password-toggle {
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    .password-toggle-img {
      width: 18px;
      height: 18px;
    }
  }
}
.code {
  display: flex;
  align-items: center;
  z-index: 10;
  height: 40px;
  cursor: pointer;
  font-size: 0px;
  img {
    max-width: 100%;
    height: 40px;
  }
}
::v-deep .el-form-item__error {
  font-size: 12px;
  color: #e85e41;
  line-height: 16px;
  text-align: left;
  font-style: normal;
  padding-top: 0px;
  padding-left: 12px;
}
::v-deep .el-input-group__append {
  border-radius: 2px;
  background: #f4f6fa;
  border: 1px solid #e3e8ef;
  padding: 0;
}
.sendCode {
  display: flex;
  justify-content: center;
  width: 100px;
  color: #0b6eff;
}
.bottombuttons {
  ::v-deep .el-button {
    width: 100%;
    height: 32px;
    padding-top: 7px;
    padding-bottom: 7px;
  }
  .changeFormButtons {
    display: flex;
    justify-content: center;
    .changeForm {
      text-align: center;
      cursor: pointer;
      font-family: Helvetica Neue, Helvetica, PingFang SC, Hiragino Sans GB,
        Microsoft YaHei, Arial, sans-serif;
      font-size: 14px;
      color: #666666;
      line-height: 19px;
      font-style: normal;
      margin: 10px 0 0 0;
      padding: 0 10px;
    }
  }
}
::v-deep .el-form-item {
  margin-bottom: 20px;
}
::v-deep .el-input__inner {
  width: 100%;
  height: 40px;
  background: #f4f6fa;
  border-radius: 3px;
  border: 1px solid #e3e8ef;
}
::v-deep .el-form-item.is-error .el-input__inner {
  border-color: #e3e8ef;
}

/* 去掉 Chrome 浏览器的数字输入框箭头 */
input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

/* 去掉 Firefox 浏览器的数字输入框箭头 */
input[type="number"] {
  -moz-appearance: textfield;
}
::v-deep.el-input .el-input__inner {
  line-height: 1px !important;
}

@media (max-width: 1440px) {
  .login-block {
    top: 120px !important;
  }
}
</style>
